﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T.FAS.Runtime.MF.Activities
{
    internal class OperationReTry
    {
        /// <summary>
        /// 重试
        /// </summary>
        /// <typeparam name="T">任务返回值类型</typeparam>
        /// <param name="func">待执行的任务</param>
        /// <param name="maxRetryCount">重试次数</param>
        /// <returns></returns>
        public static async Task<T> TryOperation<T>(Func<Task<T>> func, int maxRetryCount = 3,int delaySeconds =10)
        {
            Exception lastException = null;
            var fixdMaxRetryCount = maxRetryCount > 1 ? maxRetryCount : 1;
            for (var i = 0; i < fixdMaxRetryCount; i++)
            {
                try
                {
                    var data = await func().ConfigureAwait(false);
                    return data;
                }
                catch (Exception e)
                {
                    lastException = e;
                    // SubmitLogUtil.Log($"try{i}:{e.Message}", "TryOperation");
                    await Task.Delay(TimeSpan.FromSeconds(delaySeconds)).ConfigureAwait(false);
                }
            }
            throw lastException;
        }
    }
}
